package net.huashitong.ssydt.provider.security.service.defaults;

import net.huashitong.ssydt.exceptions.ServiceException;
import net.huashitong.ssydt.provider.security.service.UserRedisService;
import net.huashitong.ssydt.provider.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 *
 */
@Component
public class DefaultsUserRedisServiceImpl implements UserRedisService {

    private static final Integer DEFAULT_TOKEN_TIMEOUT = 7200;

    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public DefaultsUserRedisServiceImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public String getTokenByUserId(String userId) {
        if (StringUtils.isBlank(userId)) {
            return "";
        }
        String keys = getKeys(userId);
        String token = stringRedisTemplate.opsForValue().get(keys);
        if (StringUtils.isNotBlank(token)) {
            return token;
        }
        return "";
    }


    @Override
    public void setToken(String userId, String value, int seconds) {
        if (StringUtils.isBlank(userId)) {
            throw new ServiceException("key is null");
        }
        String keys = getKeys(userId);
        stringRedisTemplate.opsForValue().set(keys, value, seconds, TimeUnit.SECONDS);
    }

    @Override
    public void setToken(String userId, String value) {
        setToken(userId, value, DEFAULT_TOKEN_TIMEOUT);
    }

    @Override
    public void refreshToken(String userId, int seconds) {
        if (StringUtils.isBlank(userId)) {
            throw new ServiceException("key is null");
        }
        String keys = getKeys(userId);
        stringRedisTemplate.expire(keys, seconds, TimeUnit.SECONDS);
    }

    @Override
    public void refreshToken(String key) {
        refreshToken(key, DEFAULT_TOKEN_TIMEOUT);
    }

    private String getKeys(String userId) {
        return String.format("user:%s", userId);
    }

}
